<template>
  <div class="app-container">
    <!--搜索栏start-->
    <div class="searchMultiple" style="width: 100%">
      <el-input
        v-model="searchData.number"
        placeholder="小区编号"
        clearable
        class="input"
        style="width: 10%"
        @change="numberInputChange"
      />
      <el-input
        v-model="searchData.name"
        placeholder="小区名称"
        clearable
        class="input"
        style="width: 10%"
        @change="nameInputChange"
      />
      <el-date-picker
        v-model="createTime"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="input"
        value-format="timestamp"
        style="width: 20%"
        @change="dateSelectorChange"
      />
      <el-button style="margin-left: 1%" type="primary" icon="el-icon-close" @click="clearContent()">清空</el-button>
      <el-button style="margin-left: 1%" type="primary" icon="el-icon-search" @click="search()" @keydown="enterEvent()">搜索</el-button>
      <el-button style="float: right" size="medium" type="danger" icon="el-icon-delete" @click="deletePatch()">批量删除</el-button>
      <el-button style="float: right" size="medium" type="primary" @click="addFormVisible = true">新增</el-button>
    </div>
    <!--搜索栏end-->

    <!--表格信息start-->
    <div class="tableList">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
        />
        <el-table-column
          prop="number"
          label="小区编号"
          align="center"
        />
        <el-table-column
          prop="name"
          label="小区名称"
          align="center"
        />
        <el-table-column
          prop="address"
          label="小区地址"
          align="center"
        />
        <el-table-column
          prop="area"
          label="占地面积"
          align="center"
        />
        <el-table-column
          prop="buildingCount"
          label="幢数"
          align="center"
        />
        <el-table-column
          prop="householdCount"
          label="住户数"
          align="center"
        />
        <el-table-column
          prop="greeningRate"
          label="绿化面积"
          align="center"
        />
        <el-table-column
          prop="thumbnail"
          label="缩略图"
          align="center"
        >
          <template slot-scope="scope">
            <el-image v-if="scope.row.thumbnail" :src="scope.row.thumbnail" width="100" height="50" :preview-src-list="previewList" @click="clickImage(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          prop="developersName"
          label="开发商"
          align="center"
        />
        <el-table-column
          prop="createAt"
          label="创建时间"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.createAt | formatTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="130%"
          align="center"
        >
          <template slot-scope="scope">
            <div style="display: flex;flex-direction: row;justify-content: left">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteById(scope.row.id)">删除</el-button>
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="editXiaoQu(scope.row.id)">编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--表格信息end-->

    <!--分页插件start-->
    <el-pagination
      style="margin-top: 1%;display: flex;justify-content: right"
      background
      layout="prev, pager, next"
      :page-size="size"
      :total="total"
      :current-page.sync="searchData.pageNumber"
      @current-change="currentChange"
    />
    <!--分页插件end-->
    <!--新增弹出框start-->
    <el-dialog title="新增小区" :visible.sync="addFormVisible">
      <el-form :model="addForm">
        <el-form-item label="小区编号" label-width="120px">
          <el-input v-model="addForm.number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="小区名称" label-width="120px">
          <el-input v-model="addForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="小区地址" label-width="120px">
          <el-input v-model="addForm.address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="占地面积" label-width="120px">
          <el-input v-model="addForm.area" autocomplete="off" />
        </el-form-item>
        <el-form-item label="总幢数" label-width="120px">
          <el-input v-model="addForm.buildingCount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="总户数" label-width="120px">
          <el-input v-model="addForm.householdCount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="绿化率" label-width="120px">
          <el-input v-model="addForm.greeningRate" autocomplete="off" />
        </el-form-item>
        <el-form-item label="缩略图" label-width="120px">
          <el-upload
            class="avatar-uploader"
            action="http://39.106.32.84:8080/PMSystem/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="开发商" label-width="120px">
          <el-input v-model="addForm.developersName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insertXiaoqu">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增弹出框end-->

    <!--编辑弹出框start-->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editForm">
        <el-form-item label="小区编号" label-width="120px">
          <el-input v-model="editForm.number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="小区名称" label-width="120px">
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="小区地址" label-width="120px">
          <el-input v-model="editForm.address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="占地面积" label-width="120px">
          <el-input v-model="editForm.area" autocomplete="off" />
        </el-form-item>
        <el-form-item label="总幢数" label-width="120px">
          <el-input v-model="editForm.buildingCount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="总户数" label-width="120px">
          <el-input v-model="editForm.householdCount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="绿化率" label-width="120px">
          <el-input v-model="editForm.greeningRate" autocomplete="off" />
        </el-form-item>
        <el-form-item label="缩略图" label-width="120px">
          <el-upload
            class="avatar-uploader"
            action="http://39.106.32.84:8080/PMSystem/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="开发商" label-width="120px">
          <el-input v-model="editForm.developersName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEidt">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑弹出框end-->
  </div>
</template>

<script>
import { getList, deleteById, addXiaoqu, deletePatch, editById } from '@/api/apartment'
import { parseTime } from '@/utils/index'
import { getToken } from '@/utils/auth'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      currentXiaoQuId: null, // 当前小区id
      createTime: [], // 开始时间与结束时间
      tableData: [], // 表格数据
      total: 0, // 分页插件总记录数
      size: 0, // 分页插件每页显示个数
      addFormVisible: false, // 新增弹窗是否显示
      editFormVisible: false, // 编辑弹窗是否显示
      searchData: { // 查询参数
        id: null,
        name: null, // 小区名称
        number: null, // 小区编号
        startTime: null, // 开始时间
        endTime: null, // 结束时间
        pageNumber: 1, // 接口默认的页数
        pageSize: 5 // 接口默认的每页大小
      },
      addForm: {},
      editForm: {},
      xiaoquIds: [],
      uploadHeaders: { Authorization: getToken() }, // 文件上传请求头
      imageUrl: '', // 图片预览url
      previewList: []
    }
  },
  created() {
    this.getXiaoQuList()
    window.addEventListener('keydown', this.enterEvent)
  },
  destroyed() {
    window.removeEventListener('keydown', this.enterEvent, false)
  },
  methods: {
    getXiaoQuList() {
      console.log(this.searchData.pageSize)
      this.finalSelect()
    },
    search() { // 点击搜索按钮
      if (this.createTime) {
        this.searchData.startTime = this.createTime[0]
        this.searchData.endTime = this.createTime[1]
      }
      this.finalSelect()
    },
    clearContent() { // 清空输入框方法
      this.searchData.name = null
      this.searchData.number = null
      this.searchData.startTime = null
      this.searchData.endTime = null
      this.createTime = null
      this.searchData.pageNumber = 1
      this.getXiaoQuList()
    },
    deleteById(id) { // 根据小区id删除小区
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(res => {
          if (res.code === 20000) {
            this.$message.success('删除成功！')
          } else {
            this.$message.warning('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange(val) {
      this.xiaoquIds = []
      val.forEach(value => {
        this.xiaoquIds.push(value.id)
      })
    },
    currentChange(val) { // 点击分页栏方法
      this.searchData.pageNumber = val
      this.finalSelect()
    },
    dateSelectorChange(value) { // 清空时间选择框回调方法
      if (value == null) {
        this.searchData.startTime = null
        this.searchData.endTime = null
      }
    },
    numberInputChange(value) { // 小区编号输入框chang函数
      if (value === '' || value == null) {
        this.searchData.number = null
      }
    },
    nameInputChange(value) { // 小区名称输入框chang函数
      if (value === '' || value == null) {
        this.searchData.name = null
      }
    },
    handleAvatarSuccess(res) { // 上传成功函数
      this.imageUrl = res.data
      this.addForm.thumbnail = res.data
      this.editForm.thumbnail = res.data
    },
    beforeAvatarUpload(file) { // 上传之前
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    insertXiaoqu() { // 添加小区方法
      addXiaoqu(this.addForm).then(res => {
        if (res.code === 20000) { // 新增完成之后，来到第一页
          this.$message.success('添加成功!')
          this.searchData.pageNumber = 1
          this.finalSelect() // 跳转到首页
        } else {
          this.$message.error('添加失败!')
        }
        this.addForm = {}
        this.addFormVisible = false
      })
    },
    editXiaoQu(id) { // 编辑小区按钮,数据回显
      this.currentXiaoQuId = id
      this.editFormVisible = true
      getList({
        id: id
      }).then(res => {
        this.editForm = res.data[0]
        this.imageUrl = res.data[0].thumbnail
      })
    },
    calcuPageNumber() { // 计算当前属于第几页，如果取余size正好等于0证明刚好这在这一页，否则结果加1
      return this.total % this.size === 0 ? Math.floor(this.total / this.size) : Math.floor(this.total / this.size) + 1
    },
    deletePatch() { // 根据id批量删除小区
      this.$confirm('此操作将永久删除这些记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePatch(this.xiaoquIds).then(res => {
          this.total = this.total - this.xiaoquIds.length
          const current = this.calcuPageNumber()
          this.searchData.pageNumber = current
          this.$message.success('删除成功！')
          this.finalSelect() // 跳转到当前页
        }).catch(() => {
          this.$message.error('删除失败！')
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    finalSelect() { // 封装后的查询列表方法
      getList(this.searchData).then(res => {
        if (res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          this.size = res.data.size
        } else {
          this.tableData = res.data
        }
      })
    },
    enterEvent() {
      console.log('键盘事件')
    },
    saveEidt() {
      editById(this.currentXiaoQuId, this.editForm).then(res => {
        if (res.code === 20000) {
          this.$message.success('修改成功！')
        } else {
          this.$message.error('修改失败！')
        }
        this.editFormVisible = false // 关闭弹出框
        this.finalSelect() // 刷新界面
      }).catch(() => {
        this.editFormVisible = false
        this.$message.error('修改失败！')
      })
    },
    clickImage(item) { // 点击图片方法
      this.previewList = []
      this.previewList.push(item.thumbnail)
      console.log(this.previewList[0])
    }
  }
}
</script>

<style lang="scss">
.searchMultiple{
  margin-top: 1%;
  width: 80%;
  .input{
    width: 20%;
    margin-right: 0.5%;
  }
}
.tableList{
  margin-top: 1%;
  height: 50%;
  display: flex;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
